package cn.cvs.servlet.sysUser;

import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysUserService;
import cn.cvs.util.SpringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "UpdateServlet", urlPatterns = "/sys/user/update")
public class UpdateServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet ( request, response );
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding ( "utf-8" );
        response.setContentType ( "text/html;charset=UTF-8" );
        SysUserService sysUserService= (SysUserService) SpringUtil.getBean ( "sysUserService" );

        int id= Integer.parseInt ( request.getParameter ( "id" ) );
        String realName = request.getParameter ( "realName" );
        int sex = Integer.parseInt ( request.getParameter ( "sex" ) );
        String birthday = request.getParameter ( "birthday" );
        String phone = request.getParameter ( "phone" );
        String address = request.getParameter ( "address" );
        int roleId = Integer.parseInt ( request.getParameter ( "roleId" ) );

        SysUser user=new SysUser ();
        user.setId(id);
        user.setPhone(phone);
        user.setRoleId(roleId);
        user.setRealName ( realName );
        user.setSex ( sex );
        try {
            user.setBirthday (new SimpleDateFormat("yyyy-MM-dd").parse ( birthday ) );
            user.setUpdatedUserId ( id );
            user.setUpdatedTime ( new Date (  ) );
        } catch (ParseException e) {
            e.printStackTrace ( );
        }
        user.setAddress ( address );

        int row = sysUserService.updateUser ( user );
        if (row>0){
            request.getRequestDispatcher ( "/sys/user/list" ).forward ( request, response );
        }else {
            request.getRequestDispatcher ( "/sys/user/toUpdate" ).forward ( request, response );
        }
    }
}
